<template>
  <div>
    <el-dialog title="个人考勤(小王)" :visible.sync="dialogvisible" width="850px" append-to-body class="my-dialog"
               :close-on-click-modal="false" @close="cancel">
      <div>
        <div class="signlog-header">
          <div class="signlog-header-box">
            保安信息
          </div>
          <el-form ref="form" label-width="80px" label-position="left">
            <el-row>
              <el-col :span="8">
                <el-form-item label="姓名" prop="name">
                  {{ userDetail ? userDetail.nickName : '' }}
                </el-form-item>
              </el-col>
              <!--              <el-col :span="8">-->
              <!--                <el-form-item label="驻点" prop="name">-->
              <!--                  福州国贸学原二期-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="8">
                <el-form-item label="性别" prop="name">
                  <dict-tag :options="dict.type.sys_user_sex" :value="userDetail.sex" v-if="userDetail"/>
                </el-form-item>
              </el-col>
              <!--              <el-col :span="8">-->
              <!--                <el-form-item label="职务" prop="name">-->
              <!--                  队长-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="8">
                <el-form-item label="手机号" prop="name">
                  {{ userDetail ? userDetail.phonenumber : '未填写' }}
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="userDetail">
                <el-form-item label="当前状态" prop="name">
                  <el-tag type="success" v-if="userDetail.isOnline">在线</el-tag>
                  <el-tag type="danger" v-else>离线</el-tag>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="signlog-table">
          <template v-if="pointList.length">
            <div class="attendance-search">
              <el-date-picker
                class="mr10"
                size="small"
                v-model="value1"
                type="daterange"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="handleQuery"
              >搜索
              </el-button
              >
              <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
              >重置
              </el-button>
            </div>
            <div class="my-tabs">
              <el-tabs v-model="activeName">
                <el-tab-pane :label="item.name" :name="item.id.toString()" v-for="item in pointList"></el-tab-pane>
              </el-tabs>
            </div>
            <el-table
              v-loading="loading"
              :data="tableList"
              size="mini"
            >
              <el-table-column label="时间" align="center" prop="day" width="120">
                <template slot-scope="scope">
                  {{ `${scope.row.dayName} 周${week[scope.row.week]}` }}
                </template>
              </el-table-column>
              <el-table-column label="在岗类型" align="center" prop="type" width="100">
                <template slot-scope="scope">
                  {{ scope.row.isMaster ? '主岗' : '兼岗' }}
                </template>
              </el-table-column>
              <el-table-column label="职务" align="center" prop="work" width="100">
                <template slot-scope="scope">
                  <dict-tag v-if="userPointData" :options="dict.type.sys_work_post" :value="userPointData.duties"/>
                </template>
              </el-table-column>
              <!--              <el-table-column label="岗位" align="center" prop="point">-->
              <!--                <template slot-scope="scope">-->

              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column label="班次" align="center" prop="attend">
                <template slot-scope="scope">
                  <div v-if="scope.row.cate">
                    {{ scope.row.cate.name }}
                    {{
                      `${scope.row.cate.comeTime1}-${scope.row.cate.outNext1 ? '次日' : ''}${scope.row.cate.outTime1} ${scope.row.cate.comeTime2 && scope.row.cate.comeNext2 ? '次日' : ''}${scope.row.comeTime2 || ''}${scope.row.cate.comeTime2 ? '-' : ''}${scope.row.cate.outTime2 && scope.row.cate.outNext2 ? '次日' : ''}${scope.row.cate.outTime2 || ''}`
                    }}
                  </div>
                  <div v-else>
                    休息
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="出勤状态" align="center" prop="status" width="100">
                <template slot-scope="scope">
                  <el-tag @click="checkDayLog(scope.row)" :type="scope.row.status?'success':'danger'" size="mini">
                    <span class="logDetail">{{ scope.row.statusName }}</span>
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="核算工时(h)" align="center" prop="workTime" width="100"/>
              <el-table-column label="当日轨迹" align="center" prop="workTime" width="90">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="showMapLog(scope.row)"
                    v-hasPermi="['system:project:edit']"
                  >查看轨迹
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
          <div v-else style="text-align: center;padding: 10px 0;">
            未找到相匹配的数据
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="small" plain>确 定</el-button>
      </div>
    </el-dialog>
    <attendDetail :visible.sync="attenVisible" :attendLog="attendLog" :userId="paramData" :pointsId="activeName"
                  :pointsData="pointsData"></attendDetail>
    <userDayMap :visible.sync="showMapLogVisible" :userDetail="userDetail" :pointsData="pointsData"
                :workData="workData"></userDayMap>
  </div>
</template>

<script>
import {userPointBelong, listStagnationPointUser} from "@/api/system/stagnation_point";
import {getInfoNew} from "@/api/login";
import {schedulingSign} from "@/api/system/attendLog";
import attendDetail from "./attendDetail";
import userDayMap from "@/components/MapArea/userDayMap";

export default {
  props: ['visible', 'paramData', 'monthDay'], // param 执勤点信息
  dicts: ['sys_user_sex', 'sys_work_post'],
  name: "index",
  components: {attendDetail, userDayMap},
  data() {
    return {
      dialogvisible: false,
      value1: '',
      activeName: '',
      loading: false,
      tableList: [],
      pointList: [],
      userDetail: null,
      week: ['日', '一', '二', '三', '四', '五', '六'],
      userPointData: null,
      attenVisible: false,
      attendLog: null,
      pointsData: null,
      showMapLogVisible: false,
      workData: null
    }
  },
  watch: {
    visible() {
      this.dialogvisible = this.visible
      if (this.visible) {
        this.value1 = this.$deepCopy(this.monthDay)
        console.log('paramData', this.paramData, this.monthDay)
        // this.timeLine()
        this.getUserDetail() // 查询用户详情
        this.getUserPoint() // 查询用户驻点信息列表
      } else {
        this.reset()
      }
    },
    activeName() {
      // 查询驻点考勤单用户信息记录
      for (let item of this.pointList) {
        if (Number(item.id) == this.activeName) {
          this.pointsData = this.$deepCopy(item)
        }
      }
      this.getUserPointLog()
    }
  },
  created() {
  },
  methods: {
    getUserPointLog() {
      // userId 用户ID
      // startDay 开始日期
      // endDay 结束日期 20240311
      // pointsId 驻点ID
      let value1 = this.$deepCopy(this.value1)
      let s_ = value1[0].split('-').join('')
      let e_ = value1[1].split('-').join('')
      schedulingSign({
        userId: this.paramData,
        pointsId: this.activeName,
        startDay: s_,
        endDay: e_
      }).then(res => {
        // 排班记录，根据排班为主
        for (let item of res.data) {
          const year = String(item.day).slice(0, 4);
          const month = String(item.day).slice(4, 6);
          const day = String(item.day).slice(6, 8);
          let firstDayOfMonth = new Date(year, month, day)
          // 0表示周日，1表示周一...6表示周六
          item.dayName = `${year}-${month}-${day}`
          item.week = firstDayOfMonth.getDay()
          // 先判定时间是否是大于今天 ，大于今天都是缺勤
          // status 0 异常 1 正常
          let status = 0
          let statusName = ''
          let start_Time = new Date().getTime()
          let end_Time = new Date(item.dayName).getTime() // 排班时间
          if (start_Time < end_Time) {
            // 大于今天
            status = 0
            statusName = '缺勤'
          } else if (start_Time > end_Time) {
            // 小于今天
            // signs - type 1 / 3 上班，2 / 4 下班
            // latTime 大于0 迟到时间/早退时间
            if (item.signs.length) {
              let type_ = []
              for (let sign of item.signs) {
                if (sign.type == 1 || sign.type == 3) {
                  if (sign.latTime) {
                    status = 0
                    statusName = '上班迟到'
                  } else {
                    status = 1
                    statusName = '正常'
                  }
                } else if (sign.type == 2 || sign.type == 4) {
                  if (sign.latTime) {
                    status = 0
                    statusName = '下班迟到'
                  } else {
                    status = 1
                    statusName = '正常'
                  }
                }
              }
            } else {
              // 一次打卡都没有
              status = 0
              statusName = '缺勤'
            }
          } else {
            // 就是今天
            status = 0
            statusName = '缺勤'
          }

          item.status = status
          item.statusName = statusName
        }
        this.tableList = this.$deepCopy(res.data)
      })
      // 他在该考勤组的岗位信息
      listStagnationPointUser({userId: this.paramData, pointsId: this.activeName,}).then(res => {
        console.log('getStagnationPointUser==>', res)
        this.userPointData = this.$deepCopy(res.rows[0])
      })
    },
    timeLine() {
      // 示例使用
      const dates = this.printDatesInRange(this.value1[0], this.value1[1]);
      this.tableList = dates.map(date => {
        let data_ = date.toISOString().split('T')[0]
        let time_ = data_.split('-')
        let firstDayOfMonth = new Date(data_)
        // 0表示周日，1表示周一...6表示周六
        let dayWeek = firstDayOfMonth.getDay()
        return {
          day: `${time_[1]}/${time_[2]}`,
          week: dayWeek,
          type: '主岗',
          work: '队长',
          point: '巡逻岗',
          attend: '白班07:00-19:00',
          status: '缺勤',
          time: 0
        }
      })
    },
    /** 查询单个用户详情 */
    getUserDetail() {
      getInfoNew(this.paramData).then(res => {
        this.userDetail = res.data
      })
    },
    /** 查询单个用户挂靠的驻点 */
    getUserPoint() {
      userPointBelong({userId: this.paramData}).then(res => {
        if (res.data.length) {
          this.activeName = res.data[0].id.toString()
        }
        this.pointList = res.data
        this.getUserPointLog()
      })
    },
    handleQuery() {
      this.getUserPointLog()
    },
    resetQuery() {
      this.value1 = this.$deepCopy(this.monthDay)
    },
    reset() {
      this.pointList = []
      this.value1 = ''
      this.tableList = []
    },
    submitForm() {
      this.cancel()
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    printDatesInRange(date1, date2) {
      const startDate = new Date(date1);
      const endDate = new Date(date2);
      const dateArray = [];

      let currentDate = new Date(startDate);
      while (currentDate <= endDate) {
        dateArray.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
      }

      return dateArray;
    },
    // 查看当天的打卡记录
    checkDayLog(row) {
      this.attendLog = this.$deepCopy(row)
      this.attenVisible = true
    },
    showMapLog(row) {
      this.workData = this.$deepCopy(row)
      this.showMapLogVisible = true
    }
  }
}
</script>

<style scoped>
.setting-box {
  margin-bottom: 10px;
  padding-left: 18px;
}

.setting-box-title {
  display: flex;
  align-items: center;
}

.setting-box-title-l {
  color: #000;
  margin-right: 10px;
}

.setting-box-list {
  display: flex;
  align-items: center;
  color: rgba(23, 26, 29, .6);
  font-size: 14px;
}

.signlog-header {
  border: 1px solid #777;
  border-radius: 10px;
  padding: 10px 20px;
  margin-bottom: 20px;
}

.signlog-header-box {
  font-size: 16px;
  font-weight: bold;
}

.signlog-header .el-form-item {
  margin-bottom: 5px;
}

.logDetail {
  cursor: pointer;
}
</style>
